<template>
	<view class="container ">
		<!-- <view class="left-bottom-sign"></view> -->
		<view class="back-btn yticon icon-zuojiantou-up" @click="navBack"></view>
		<!-- <view class="right-top-sign"></view> -->
		<!-- 设置白色背景防止软键盘把下部绝对定位元素顶上来盖住输入框等 -->
		<view class="wrapper">
			<!-- <view class="left-top-sign">CCNBYSHOP</view> -->
			<view class="welcome">
				<image src="../../../static/login/login-logo.png" style="width: 160rpx; height: 160rpx"></image>
				<view class="" style="color: #111111;font-size: 36rpx">
					OJ原聚酒小二
				</view>
			</view>
			<view style="margin: 0 60rpx 40rpx 60rpx;">
				<!-- <u-tabs :list="list" :active-item-style="active" :bar-style="tabActive" :is-scroll="false"
					:current="current" @change="change"></u-tabs> -->
			</view>
			<view v-if="current==0" >
				<!-- <view style="display: flex;justify-content: center;align-content: center;margin: 10rpx 140rpx;">
					<view style="text-align: center;flex: 1;" @click="wxLogin">
						<view style="margin-bottom: 10rpx;">
							<u-icon name="weixin-circle-fill" size="95" color="#108040"></u-icon>
						</view>
						<view>微信登陆</view>
					</view>
				</view> -->
				
				<view class="input-content">
					<!-- <view class="input-item">
						<text class="tit">用户名</text>
						<input type="text" v-model="form.userName" placeholder="请输入用户名" maxlength="11" data-key="mobile"
							@input="inputChange" />
					</view>
					<view class="input-item">
						<text class="tit">密码</text>
						<input type="mobile" v-model="form.password" placeholder="请输入您的用户名密码"
							placeholder-class="input-empty" maxlength="20" password data-key="password"
							@input="inputChange" />
					</view> -->
					<view class="input-item">
						<!-- <text class="tit">手机号</text> -->
						<input type="number" v-model="form.phoneNumber" placeholder="请输入手机号码" maxlength="11"
							data-key="mobile" @input="inputChange" />
					</view>
					<view class="input-item">
						<input type="number" v-model="form.code" placeholder="验证码"
							placeholder-class="input-empty" maxlength="20" data-key="mobile"
							@input="inputChange" />
						<view class="mobileno-input-right">
							<a class="sendCodeBtn" @click="sendCode" v-if="verification">获取验证码</a>
							<a class="sendCodeBtn" v-if="!verification">{{ timer }} 秒后重新获取</a>
						</view>
					</view>
					<!-- <div style="display: flex;">
						<view class="input-item">
							<view>
								<view style="flex: 1;">
									<text class="tit">验证码</text>
									<input type="text" v-model="form.code" placeholder="验证码"
										placeholder-class="input-empty" maxlength="20" data-key="mobile"
										@input="inputChange" />
								</view>
							</view>
						</view>
						<view style="border-radius: 10rpx;display: flex;align-items: center;margin-left: 20rpx;">
							<image @click="getRandomCode" style="width: 200rpx;height: 100rpx;" :src="form.src" mode="">
							</image>
						</view>
					</div> -->
					<button class="confirm-btn" @click="toLogin">登录</button>
				</view>

			</view>
			<view v-if="current==1">
				<view class="input-content">
					<!-- <view class="input-item">						<text class="tit">用户名</text>						<input type="text" v-model="form.userName" placeholder="请输入用户名" maxlength="11" data-key="mobile"							@input="inputChange" />					</view>					<view class="input-item">						<text class="tit">密码</text>						<input type="mobile" v-model="form.password" placeholder="请输入您的用户名密码"							placeholder-class="input-empty" maxlength="20" password data-key="password"							@input="inputChange" />					</view> -->
					<view class="input-item">
						<!-- <text class="tit">手机号</text> -->
						<input type="number" v-model="form.phoneNumber" placeholder="请输入手机号码" maxlength="11"
							data-key="mobile" @input="inputChange" />
					</view>
					<view class="input-item">
						<input type="number" v-model="form.code" placeholder="验证码"
							placeholder-class="input-empty" maxlength="20" data-key="mobile"
							@input="inputChange" />
						<view class="mobileno-input-right">
							<a class="sendCodeBtn" @click="sendCode" v-if="verification">获取验证码</a>
							<a class="sendCodeBtn" v-if="!verification">{{ timer }} 秒后重新获取</a>
						</view>
					</view>

				</view>

				<button class="confirm-btn" @click="toLogin" :disabled="logining">登录</button>

				<!-- 		<view class="forget-section" @click="toForgetPassword">
					忘记密码?
				</view> -->
			</view>
			<view v-show="false" style="margin: 20rpx auto; width: 630upx;">
				<u-button shape="circle" open-type="getPhoneNumber" @getphonenumber="phoneLogin">微信手机号登陆</u-button>
			</view>
			
			<view v-show="false" class="forget-section" @click="toForgetPassword">
				忘记密码?
			</view>
			<view class="forget-section">
				还没有账号?
				<text @click="toRegister">马上注册</text>
			</view>
		<!-- 	
			<view style="position: absolute;bottom: 30rpx;width: 100%;text-align: center;">
				<u-checkbox
				:customStyle="{marginBottom: '18rpx',marginTop:'18rpx'}"
				:label="22"
				:name="11">
				</u-checkbox><text style="color:#CA8248;">《用户协议》</text>和<text style="color: #CA8248;">《隐私政策》</text>
			</view> -->
		</view>

	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';

	export default {
		data() {
			return {
				form: {
					userName: '',
					password: '',
					phoneNumber: '',
					loginStatus: 0, // 0: 普通用户登录， 1：商户登录
					sourceType: 'APP',
					codeKey: '',
					code: '',
					src: '',

				},
				active: {
					color: '#7EAFA5'
				},
				tabActive: {
					background: '#7EAFA5'
				},
				list: [
					{
					name: '用户登录'
				}, 
				{
					name: '商家登录'
				}],
				current: 0,
				mobile: '',
				password: '',
				userName: '',
				logining: false,
				to: '',
				wechatUserInfo: {},
				tips: '',
				seconds: 10,
				submitting: false,
				verification: true, // 通过v-show控制显示获取还是倒计时
				timer: 60, // 定义初始时间为60s

			}
		},
		onLoad(options) {
			this.form.codeKey = uni.getStorageSync("codeKey")
			this.getRandomCode()
		},
		onShow() {
			// if (this.hasLogin) {
			// 	uni.navigateBack()
			// }
		},
		computed: {
			...mapState(['applicationConfig', 'apiBaseUrl', 'openid', 'session_key', 'hasLogin'])
		},
		methods: {
			...mapMutations(['login', 'setToken']),
			
			async wxLogin() {
				if (this.openid == null) {					
					uni.login({
						success: (res) => {
							console.log(res);
							this.$api.request.getOpenid({
								code: res.code
							}, res => {
								console.log(res);
								if (res.code == 200) {
									let data = JSON.parse(res.data)
									this.$store.commit("setOpenId", data)
									console.log(data.openid);
								}
							})
						}
					})
				}
				uni.getUserProfile({
					desc: "获取你的昵称、头像、地区及性别",
					success: (res) => {
						console.log(res)
						this.$api.request.getWxUser({
							wechatId: this.openid
						}, resp => {
							if (resp.code == 200 && resp.data != 404) {
								this.$u.toast("微信登陆成功！", 4000)
								this.$store.commit("setToken", resp.data.tokenValue)
								this.$store.commit("login", resp.data);
								uni.setStorageSync('authStatus', true)
								this.$api.request.userInfo({
									type: 'application/x-www-form-urlencoded',
								}, res => {
									// console.log(res);
									if (res.code == 200) {						
										uni.setStorageSync('userInfo', res.data)
									}
								})
								setTimeout(resp => {
									uni.switchTab({
										url: "/pages/sys/home/index"
									})
								}, 1000)
							}
							if (resp.data == 404) {
								this.$api.msg("用户不存在，前往注册！")
								setTimeout(resp => {
									uni.navigateTo({
										url: "/pages/sys/common/register"
									})
								}, 1000)
							}
						
						})
					}
				})
				
			},
			phoneLogin(e) {
				// console.log(e);
				if (typeof(e.detail.iv) != "undefined") {
					this.$api.request.getPhone({
						encryptedData: e.detail.encryptedData,
						iv: e.detail.iv,
						sessionKey: this.session_key,
						sourceType: "APP"
					}, res => {
						if (res.code == 200 && res.data != 404) {
							this.$store.commit("setToken", uni.getStorageSync(
								'userToken'))
							this.$store.commit("setToken", res.data.tokenValue)
							this.$store.commit("login", res.data);
							setTimeout(res => {
								uni.switchTab({
									url: "/pages/sys/home/index"
								})
							}, 1000)
						}
						if (res.data == 404) {
							this.$api.msg("用户不存在，前往注册！")
							setTimeout(res => {
								uni.navigateTo({
									url: "/pages/sys/common/register"
								})
							}, 1000)
						}
					})
					// this.$u.post("/wx/authLogin",{
					// encryptedData: e.detail.encryptedData,
					// iv: e.detail.iv,
					// sessionKey: this.session_key,
					// openId: this.openid,
					// phone:this.phone,
					// 	f:2
					// }).then(res=>{
					// 	console.log(res);
					// 	this.$store.commit("getPhone",res.data.phoneNumber)
					// 	// this.phone = res.phoneNumber
					// 	console.log(this.phone);
					// })
				} else {
					this.$u.toast("未获取手机号")
				}
			},
			getRandomCode() {
				let random = Math.random().toFixed(6).slice(-6)
				this.form.codeKey = random
				console.log(this.apiBaseUrl);
				this.form.src = this.apiBaseUrl + "verifycode/getimage?codeKey=" + random
				// this.$api.request.getCode({
				// 	codeKey: Math.random().toFixed(6).slice(-6),
				// 	type: 'application/x-www-form-urlencoded'
				// }, res => {
				// 	var blob = new Blob([res], {
				// 		type: "image/png"
				// 	});
				// 	var url = URL.createObjectURL(blob);
				// 	console.log(res);

				// 	console.log("url:",url);
				// })
			},
			change(e) {
				console.log(e);
				this.current = e
				this.form.loginStatus = e
			},
			inputChange(e) {
				const key = e.currentTarget.dataset.key;
				this[key] = e.detail.value;
			},
			navBack() {
				uni.switchTab({
					url: '/pages/sys/home/index'
				})
			},
			toRegister() {
				uni.navigateTo({
					url: '/pages/sys/common/register?to=' + escape(this.to)
				})
			},
			toForgetPassword() {
				uni.navigateTo({
					url: '/pages/sys/common/forgetPassword'
				})
			},
			toLogin() {
				const that = this
				const {
					userName,
					password,
					code
				} = this.form;
				this.form.wechatId = uni.getStorageSync('openId')
				if (this.current == null) {
					console.log(this.form);
					if (userName == '') {
						this.$api.msg('用户名不能为空');
					} else if (password == '') {
						this.$api.msg('密码不能为空');
					} else if (this.form.code == '') {
						this.$api.msg('验证码不能为空');
					} else {
						this.$api.request.doLogin(this.form, res => {
							// console.log(res);
							that.$u.toast(res.message)
							if (res.code == 200) {
								setTimeout(() => {
									uni.setStorageSync('authStatus', true)
									this.$api.request.userInfo({
										type: 'application/x-www-form-urlencoded',
									}, res => {
										// console.log(res);
										if (res.code == 200) {						
											uni.setStorageSync('userInfo', res.data)
										}
									})
									this.setToken(res.data.tokenValue)
									setTimeout(() => {
										uni.switchTab({
											url: '/pages/sys/user/index'
										})
									}, 1000)
								},50)

							}
						});
					}

				} else {
					console.log(this.form);
					if (!this.$api.util.validateMobileNo(this.form.phoneNumber)) {
						this.$api.msg('手机号码格式错误');
					} else if (this.form.code == '') {
						this.$api.msg('验证码不能为空');
					} else {
						this.$api.request.doPhoneLogin(this.form, res => {
							console.log("log", res);
							this.$u.toast(res.message)
							if (res.code == 200) {
								uni.setStorageSync('authStatus', true)
								this.setToken(res.data.tokenValue)
								that.$api.request.userInfo({
									type: 'application/x-www-form-urlencoded',
								}, res => {
									if(res.code == 200){
										uni.setStorageSync('userInfo', res.data)
										uni.setStorageSync('authStatus', true)
										setTimeout(() => {
											uni.switchTab({
												url: '/pages/sys/user/index'
											})
										}, 1000)
									}
								})
							}
						});
					}

				}

			},
			codeChange(text) {
				this.tips = text;
			},

			end() {
				// this.$u.toast('倒计时结束');
			},
			start() {
				// this.$u.toast('倒计时开始');
			},
			sendCode() {
				if (!this.$api.util.validateMobileNo(this.form.phoneNumber)) {
					this.$api.msg('手机号码格式错误');
					return
				} else {
					this.$api.request.getPhoneCode({
						phone: this.form.phoneNumber,
						temp: 'login'
					}, res => {
						// console.log(res);
						this.$u.toast(res.message);
						if (res.code == 200) {
							this.$api.msg('验证码已发送');

							this.form.codeKey = res.data.codeKey
							uni.setStorage({
								key: 'codeKey',
								data: res.data.codeKey
							})
							this.timer = 60
							this.verification = false
							this.countDown() // 执行验证码计时
						}
					})


				}




				// this.$api.request.sms({
				// 	type: 'MOBILE',
				// 	mobileCountryCode: '86',
				// 	mobileNo: mobileNo
				// }, loginRes => {
				// 	if (loginRes.body.status.statusCode === '0') {
				// 		this.$api.msg('验证码已发送');
				// 		this.timer = 5
				// 		this.verification = false
				// 		this.countDown() // 执行验证码计时
				// 	} else {
				// 		this.$api.msg(loginRes.body.status.errorDesc);
				// 	}
				// });
			},
			// 验证码倒计时
			countDown() {
				let auth_timer = setInterval(() => {
					// 定时器设置每秒递减
					this.timer-- // 递减时间
					uni.setStorage({
						key: 'timer',
						data: this.timer,
						success: function() {}
					})
					if (this.timer <= 0) {
						this.verification = true // 60s时间结束还原v-show状态并清除定时器
						clearInterval(auth_timer)
					}
				}, 1000)
			},
		},

	}
</script>

<style lang='scss'>
	page {
		background: #fff;
	}

	.container {
		padding-top: 75px;
		/* position: relative; */
		width: 100vw;
		height: 100vh;
		height: 100%;
		overflow: hidden;
		background: #fff;
		background-image: url('../../../static/login/login-bg.png');
		background-size: contain;
		background-repeat: no-repeat;
		background-position: top;
	}

	.wrapper {
		/* position: relative; */
		z-index: 90;
		/* background: #fff; */
		padding-bottom: 40upx;
		padding-top:160upx;
	}

	.back-btn {
		position: absolute;
		left: 40upx;
		z-index: 9999;
		padding-top: var(--status-bar-height);
		top: 40upx;
		font-size: 40upx;
		color: $font-color-dark;
	}

	.application-logo {
		text-align: center;

		image {
			width: 200upx;
			height: 200upx;
		}
	}

	.application-name {
		margin-top: 20upx;
		text-align: center;
		color: $font-color-base;
	}

	.left-top-sign {
		font-size: 120upx;
		color: $page-color-base;
		position: relative;
		left: -16upx;
	}

	.right-top-sign {
		position: absolute;
		top: 80upx;
		right: -30upx;
		z-index: 95;

		&:before,
		&:after {
			display: block;
			content: "";
			width: 400upx;
			height: 80upx;
			background: #b4f3e2;
		}

		&:before {
			transform: rotate(50deg);
			border-radius: 0 50px 0 0;
		}

		&:after {
			position: absolute;
			right: -198upx;
			top: 0;
			transform: rotate(-50deg);
			border-radius: 50px 0 0 0;
			/* background: pink; */
		}
	}

	.left-bottom-sign {
		position: absolute;
		left: -270upx;
		bottom: -320upx;
		border: 100upx solid #d0d1fd;
		border-radius: 50%;
		padding: 180upx;
	}

	.welcome {
		position: relative;
		text-align: center;
		/* top: -90upx; */
		font-size: 46upx;
		color: #555;
		text-shadow: 1px 0px 1px rgba(0, 0, 0, .3);
		margin-bottom: 120rpx;
	}

	.input-content {
		padding: 0 60upx;
	}

	.input-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 28rpx 48rpx;
		/* background: $page-color-light; */
		border-radius: 92rpx;
		margin-bottom: 48rpx;
		box-shadow:  0px 4rpx 20rpx 0px rgba(0,0,0,0.1);;
		
		&:last-child {
			margin-bottom: 0;
		}
		.tit {
			height: 50upx;
			line-height: 56upx;
			font-size: $font-sm+2upx;
			color: $font-color-base;
		}

		input {
			font-size: 30rpx;
			color: $font-color-dark;
			flex: 1;
			overflow: hidden;
		}
		.sendCodeBtn{
			font-size: 30rpx;
			color: #CA8248;
		}
	}

	.confirm-btn {
		width: 630upx;
		height: 76upx;
		line-height: 76upx;
		border-radius: 50px;
		margin-top: 70upx;
		/* background: linear-gradient(328deg, #03D289 0%, #009B65 100%); */
		background: linear-gradient(135deg, #FFE5B2 0%, #C67A40 100%);
		color: #fff;
		font-size: $font-lg;

		&:after {
			border-radius: 100px;
		}
	}

	.forget-section {
		font-size: $font-sm+2upx;
		color: #444444;
		text-align: center;
		margin-top: 40upx;
	}

	.register-section {
		position: absolute;
		left: 0;
		bottom: 50upx;
		width: 100%;
		font-size: $font-sm+2upx;
		color: $font-color-base;
		text-align: center;

		text {
			color: $font-color-spec;
			margin-left: 10upx;
		}
	}
</style>
